<?PHP
final class Response
{
    private $retval = array();
    private $error_cnt = 0;
    private $error = array();
    public function __construct(){}
    
    //錯誤累計
    public function addError()//:Void
    {
        $this->error_cnt++;
    }
    
    //是否有錯
    public function hasError()//:Boolean
    {
        return 0 !== $this->error_cnt;
    }

    //添加錯誤訊息
    public function pushError($val, $key=NULL)//:Void
    {
        self::push($this->error, $val, $key);
        $this->addError();
    }
    
    //將所有錯誤組成字串
    public function err2string($separator="\n")//:String
    {
        return join($separator, $this->error);
    }
    
    //添加一段訊息
    public function pushRetval($val, $key=NULL)//:Void
    {
        self::push($this->retval, $val, $key);
    }
    
    //取得最後結果
    public function getResult($include_error=false)//:Array
    {
        $retval = array(
            'ret'=>$this->retval,
            'result'=> ! $this->hasError()
        );
        if ($include_error)
        {
            $retval['error'] = $this->error;
        }
        return $retval;
    }
    
    //提供直接物件轉字串的方法
    public function __toString()//:String
    {
        return json_encode($this->getResult(true));
    }
    
    //私有方法,快速組陣列
    private static function push(array &$arr, $val, $key=NULL)//:Void
    {
        if (NULL===$key)
        {
            $arr[] = $val;
        }
        else if ( ! isset($arr[$key]))
        {
            $arr[$key] = $val;
        }
        else
        {
            $arr[$key] = (array)$arr[$key];
            $arr[$key][] = $val;
        }
    }
}
?>
